"""
-- coding: utf-8 --
@Time : 2023/8/1
@Author : 张书译
@Describe:api连接方式方法封装
"""

import json
import requests
import config
from urllib3 import encode_multipart_formdata
from Logger import logger


class RequestMethod:
    """
    接口请求
    """

    @staticmethod
    def send_delete(url, data, headers=None):
        """
        发送delete请求
        :param headers:
        :param url: url
        :param data: data
        :return: res
        """
        try:
            res = requests.request("DELETE", url, headers=headers, data=data).json()
            return res
        except Exception as e:
            res = requests.request("DELETE", url, headers=headers, data=data.encode('utf-8')).text.encode('utf8')
            logger.debug(res)
            logger.debug(f"错误在这里：{e}")
            return None

    @staticmethod
    def send_post(url, data, headers=None):
        """
        发送post请求
        :param headers:
        :param url: url
        :param data: data
        :return: res
        """
        try:
            res = requests.request("POST", url, headers=headers, data=data).json()
            return res
        except Exception as e:
            res = requests.request("POST", url, headers=headers, data=data).text.encode('utf8')
            logger.error(res)
            logger.error(f"错误在这里：{e}")
            return None

    @staticmethod
    def send_post_json(url, data, headers=None):
        """
        发送post请求
        :param headers:
        :param url: url
        :param data: data
        :return: res
        """
        try:
            res = requests.request("POST", url, headers=headers, data=data.encode('utf-8')).json()
            return res
        except Exception as e:
            res = requests.request("POST", url, headers=headers, data=data.encode('utf-8')).text.encode('utf8')
            logger.error(res)
            logger.error(f"错误在这里：{e}")
            return None

    @staticmethod
    def send_get(url, headers=None):
        """
        发送get请求
        :param headers:
        :param url: url
        :return: res
        """
        try:
            res = requests.request("GET", url, headers=headers).json()
            return res
        except Exception as e:
            res = requests.request("POST", url, headers=headers).text.encode('utf8')
            logger.error(res)
            logger.error(f"错误在这里：{e}")
            return None

    @staticmethod
    def send_get_download(url, data, headers=None, name=None):
        """
        发送get请求
        :param name:
        :param headers:
        :param url: url
        :param data: data
        :return: res
        """
        try:
            res = requests.request("GET", url, headers=headers, data=data)
            fp = open(config.DownloadPath + f'/{name}.xls', "wb")
            fp.write(res.content)
            fp.close()
            return config.DownloadPath + f'/{name}.xls'
        except Exception as e:
            logger.error(f"错误在这里：{e}")
            return None

    @staticmethod
    def post_files(url, header, data, filepath, filename=None):
        """
        参数
        :param data:
        :param header:
        :param url:
        :param filepath: (optional) Dictionary of ``'name':
        :param filename:
        """
        if data != {} and filename is None:
            data['streamFile'] = (filepath.split("\\")[-1], open(filepath, 'rb').read())
        else:
            data['file'] = (filepath.split("\\")[-1], open(filepath, 'rb').read())
        encode_data = encode_multipart_formdata(data)
        data = encode_data[0]
        header['Content-Type'] = encode_data[1]
        res = requests.post(url, headers=header, data=data).json()
        return res

    @staticmethod
    def send_put(url, data, headers=None):
        """
        发送put请求
        :param headers:
        :param url: url
        :param data: data
        :return: res
        """
        try:
            res = requests.request("PUT", url, headers=headers, data=data.encode('utf-8')).json()
            return res
        except Exception as e:
            try:
                res = requests.request("PUT", url, headers=headers, data=data.encode('utf-8')).text.encode('utf8')
                logger.error(res)
                logger.error(f"错误在这里：{e}")
                return None
            except Exception as e:
                logger.error(f"错误在这里：{e}")
                pass

    def run_main(self, url, method, data, header, filename=None, filepath=None, name=None):
        """
        执行方法，传递method， URL， data参数
        :param name: excel表格名称
        :param filepath:
        :param filename:
        :param data:
        :param method:
        :param url:
        :param header:
        :return:
        """
        try:
            if method.lower() == "get":
                url = self.payload(url, data)
                res = self.send_get(url, header)
            elif method.lower() == "delete":
                res = self.send_delete(url, data, header)
            elif filename is not None or filepath is not None:
                res = self.post_files(url, header, data, filepath, filename)
            elif method.lower() == "put":
                res = self.send_put(url, json.dumps(data), header)
            elif method.lower() == "post":
                res = self.send_post(url, data, header)
            elif method.lower() == "get_download":
                res = self.send_get_download(url, data, header, name=name)
            else:
                res = self.send_post_json(url, json.dumps(data), header)
            logger.info(f"连接:{url}")
            logger.info(f"请求头:{header}")
            logger.info(f"参数:{data}")
            logger.info(f"接口返回:{res}")
            return res
        except Exception as e:
            logger.error(f"错误在这里：{e}")
            return None

    @staticmethod
    def payload(url, data):
        """GET请求整理参数"""
        k = '?'
        for key, vlu in data.items():
            k = f"{k}{key}={vlu}&"
        url_list = url + k[:-1]
        return url_list
